import $ from 'jquery';
import router from '@/router/index';

const ModuleUser = {
    state: {
        id: "",
        username: "",
        photo: "",
        identity: "",
        token: "",
        is_login: false,
        records: [],
        repair_count: 0,
        unread_event_count: 0,
        pulling_info: true,     // 是否正在从云端拉取信息
    },
    getters: {
    },
    mutations: {
        updatePhoto(state, photo) {
            state.photo = photo;
        },
        updateRecords(state, records) {
            state.records = records;
        },
        updateRepairCount(state, repair_count) {
            state.repair_count = repair_count;
        },
        updateUnreadEventCount(state, unread_event_count) {
            state.unread_event_count = unread_event_count;
        },
        updateUser(state, user) {   // user是自己定义的参数
            state.id = user.id;
            state.username = user.username;
            state.photo = user.photo;
            state.identity = user.identity;
            state.token = user.token;
            state.is_login = user.is_login;
        },
        logout(state) {
            localStorage.removeItem("jwt_token");
            state.id = "";
            state.username = "";
            state.photo = "";
            state.identity = "";
            state.token = "";
            state.is_login = false;
            router.push({name: 'login'});
        },

        updatePullingInfo(state, pulling_info) {
            state.pulling_info = pulling_info;
        }
    },
    actions: {
        login(context, data) {  // context是传一些API，data是自己定义的参数
            $.ajax({
                url: "http://localhost:3000/api/account/token",
                type: "POST",
                data: {
                    username: data.username,
                    password: data.password,
                },
                success(resp) {
                    const token = resp.token;
                    localStorage.setItem("jwt_token", token);

                    $.ajax({
                        url: "http://localhost:3000/api/account/info",
                        type: "GET",
                        headers: {      // jwt验证写法
                            'Authorization': "Bearer " + token,
                        },
                        success(resp) {     
                            context.commit("updateUser", {
                                ...resp,    // 将resp解构
                                token: token,
                                is_login: true,
                            });
                            data.success();
                        },
                    })
                },
                error() {
                    data.error();
                }
            });
        },
    },
    modules: {
    }
};

export default ModuleUser;